﻿import QtQuick
import QtQuick.Layouts
import QtQuick.Window
import QtQuick.Controls
import QtQuick.Dialogs
import QtCore
import FilUI

import "../controls"

FilScrollablePage {
    id: control

    property int rightScrollableMargin: 17
    property int frameSpacing: 12
    property int footerHeight: 8

    FilFrame {
        Layout.fillWidth: true
        Layout.rightMargin: control.rightScrollableMargin
        // Layout.topMargin: 20
        height: 100
        padding: 10
        color: "transparent"
        ColumnLayout {
            spacing: 5
            Row {
                spacing: 5
                FilText {
                    text: qsTr("Refresh Interval (Unit: seconds)")
                    font: FilTextStyle.BodyStrong
                    Layout.bottomMargin: 4
                }
                FilIconButton { // 帮助按钮
                    id: id_filiconbutton__wdir_help
                    // topPadding: 1
                    anchors.verticalCenter: parent.verticalCenter
                    text: qsTr("Help")
                    iconSource: FilIcons.Info
                    iconSize: 18
                    color: Qt.rgba(0, 0, 0, 0)
                    iconColor: {
                        if (!enabled) {
                            return Qt.rgba(161/255, 161/255, 161/255, 1)
                        }
                        if (pressed) {
                            return Qt.rgba(0, 0, 0, 0.6)
                        }
                        return hovered ? Qt.rgba(0, 0, 0, 0.3) : Qt.rgba(0, 0, 0, 1)
                    }
                    verticalPadding: 0
                    horizontalPadding: 0
                    background: Rectangle {
                        radius: parent.radius
                        color: parent.color
                        FilFocusRectangle {
                            visible: parent.parent.activeFocus
                        }
                    }
                    onClicked: {
                        id_filsheet__interval.open()
                    }
                }
                FilSheet {
                    id: id_filsheet__interval
                    title: qsTr("Refresh Interval (Unit: seconds)")
                    size: 200
                    FilText {
                        leftPadding: 10
                        rightPadding: 10
                        text: qsTr('This setting determines the heartbeat interval for server connections.
Too long an interval may cause session timeouts, forcing reauthentication.
Supports up to 3600 seconds (set to 0 to disable heartbeats).')
                    }
                }
            }
            FilSpinBox {
                value: SettingsHelper.getHeartbeatInterval()
                editable: true
                to: 3600
                onValueModified: {
                    SettingsHelper.saveHeartbeatInterval(value)
                }
            }
        }
    }
    FilFrame {
        id: id_filframe__download
        Layout.fillWidth: true
        Layout.topMargin: 10
        Layout.rightMargin: control.rightScrollableMargin
        color: "transparent"
        padding: 10
        ColumnLayout {
            width: parent.width
            spacing: 5
            FilText {
                text: qsTr("Download location")
                font: FilTextStyle.BodyStrong
                Layout.bottomMargin: 4
            }
            RowLayout {
                width: parent.width
                spacing: 5
                FilTextBox {
                    id: id_filtextbox__downloaddir
                    Layout.fillWidth: true
                    readOnly: true
                    Component.onCompleted: {
                        text = SettingsHelper.getAppDownloadDir()
                    }
                }
                FilButton {
                    Layout.rightMargin: 2
                    text: qsTr("Change")
                    onClicked: {
                        id_folderdialog__downloaddir.open()
                    }
                }
                FolderDialog {
                    id: id_folderdialog__downloaddir
                    title: qsTr("Open Folder")
                    currentFolder: {
                        if (FilTools.checkDirExist(id_filtextbox__downloaddir.text)) {
                            return FilTools.getUrlByFilePath(control.wdir)
                        }
                        return StandardPaths.standardLocations(StandardPaths.DownloadLocation)[0]
                    }
                    onAccepted: {
                        var text = FilTools.toLocalPath(selectedFolder).replace(/\\/g, "/")
                        id_filtextbox__downloaddir.text = text
                        SettingsHelper.saveAppDownloadDir(text)
                    }
                }
            }
        }
    }
    FilFrame {
        visible: false
        Layout.fillWidth: true
        Layout.topMargin: 10
        Layout.rightMargin: control.rightScrollableMargin
        height: 50
        padding: 10
        color: "transparent"
        // 勾选之后会持续监听web的文件列表时间，一旦有文件更新就下载对应监听文件
        FilCheckBox {
            text: qsTr("Enable file download monitoring")
            anchors.verticalCenter: parent.verticalCenter
            onClicked: {
                showInfo(qsTr("Your changes have been saved."))
            }
        }
    }
    FilFrame {
        visible: false
        Layout.fillWidth: true
        Layout.topMargin: 10
        Layout.rightMargin: control.rightScrollableMargin
        height: 50
        padding: 10
        // 勾选之后会持续监听本地文件，一旦文件有变化就自动上传到对应目录
        color: "transparent"
        FilCheckBox {
            text: qsTr("Enable file upload monitoring")
            anchors.verticalCenter: parent.verticalCenter
            onClicked: {
                showInfo(qsTr("Your changes have been saved."))
            }
        }
    }
    FilFrame {
        id: id_filframe__language
        Layout.fillWidth: true
        Layout.topMargin: 10
        Layout.rightMargin: control.rightScrollableMargin
        color: "transparent"
        padding: 10
        ColumnLayout {
            spacing: 5
            FilText {
                text: qsTr("Language")
                font: FilTextStyle.BodyStrong
                Layout.bottomMargin: 4
            }
            Flow {
                spacing: 5
                Repeater {
                    model: TranslateHelper.languages
                    delegate: FilRadioButton {
                        checked: TranslateHelper.current === modelData
                        text: modelData
                        clickListener: function() {
                            TranslateHelper.current = modelData
                            SettingsHelper.saveLanguage(TranslateHelper.current)
                            TranslateHelper.switchLanguage(TranslateHelper.current)
                        }
                    }
                }
            }
        }
    }
    FilFrame {
        id: id_filframe__agent
        Layout.fillWidth: true
        Layout.topMargin: 10
        Layout.rightMargin: control.rightScrollableMargin
        height: 100
        padding: 10
        color: "transparent"
        property alias testing: id_filloadingbutton__test.loading
        property bool lastTestResult: false
        property int proxy_type: 0
        property string server: ""
        property string port: ""
        property string username: ""
        property string password: ""
        ColumnLayout {
            spacing: 5
            FilText {
                text: qsTr("Network Agent")
                font: FilTextStyle.BodyStrong
                Layout.bottomMargin: 4
            }
            RowLayout {
                spacing: 10
                FilComboBox {
                    id: id_filcombobox__agentMode
                    model: ListModel {
                        id: id_listmodel__agent
                        ListElement { text: qsTr("No Agent") }
                        ListElement { text: qsTr("HTTP Proxy") }
                        ListElement { text: qsTr("SOCKS5 Proxy") }
                    }
                    onActivated: (index) => {
                        console.log("index:", index)
                        if (index === 1) {
                            if (id_grid__agent.port.length <= 0) {
                                id_grid__agent.port = "80"
                            }
                        } else if (index === 2) {
                            if (id_grid__agent.port <= 0) {
                                id_grid__agent.port = "1080"
                            }
                        }
                    }
                }
                FilLoadingButton {
                    id: id_filloadingbutton__test
                    Layout.alignment: Qt.AlignVCenter
                    text: qsTr("Test")
                    disabled: {
                        if (id_filcombobox__agentMode.currentIndex === 0) {
                            return true
                        }
                        return false
                    }
                    onClicked: {
                        id_filframe__agent.lastTestResult = false
                        if (id_grid__agent.server.length <= 0) {
                            showError(qsTr("This agent is not usable."))
                            return
                        }
                        var url = SettingsHelper.getWebUrl()
                        console.log("TestProxyUrl=", url)
                        var proxyType
                        switch (id_filcombobox__agentMode.currentIndex) {
                        case 1: proxyType = NetworkProxyType.HttpProxy; break;
                        case 2: proxyType = NetworkProxyType.Socks5Proxy; break;
                        }
                        id_filframe__agent.proxy_type = proxyType
                        console.log("type:%1 server:%2 port:%3 username:%4 password:%5"
                                    .arg(proxyType)
                                    .arg(id_grid__agent.server)
                                    .arg(id_grid__agent.port)
                                    .arg(id_grid__agent.username)
                                    .arg(id_grid__agent.password))
                        Network.get(url)
                        .setProxy(proxyType, id_grid__agent.server, Number(id_grid__agent.port), id_grid__agent.username, id_grid__agent.password)
                        .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0")
                        .bind(id_filframe__agent)
                        .go(id_networkcallable_test)
                    }
                }
                FilButton {
                    Layout.alignment: Qt.AlignVCenter
                    disabled: {
                        if (id_filcombobox__agentMode.currentIndex === 0) {
                            return false
                        }
                        return !id_filframe__agent.lastTestResult
                    }
                    text: qsTr("Confirm")
                    onClicked: {
                        if (id_filcombobox__agentMode.currentIndex === 0) {
                            SettingsHelper.saveAppAgentMode(NetworkProxyType.NoProxy)
                        } else {
                            SettingsHelper.saveAppAgentMode(id_filframe__agent.proxy_type)
                            SettingsHelper.saveAppAgentServer(id_filframe__agent.server)
                            SettingsHelper.saveAppAgentPort(Number(id_filframe__agent.port))
                            SettingsHelper.saveAppAgentUsername(id_filframe__agent.username)
                            SettingsHelper.saveAppAgentPassword(id_filframe__agent.password)
                        }
                        id_filframe__agent.initAgentInfo()
                        showInfo(qsTr("Your changes have been saved."))
                    }
                }
            }
            Grid {
                id: id_grid__agent
                Layout.topMargin: 5
                columns: 2
                rows: 2
                spacing: 10
                visible: {
                    if (id_filcombobox__agentMode.currentIndex === 0) {
                        return false
                    }
                    return true
                }
                property int itemWidth: 270
                property int itemHeight: 30
                property int itemTextWidth: 80
                property alias server: id_filtextbox__server.text
                property alias port: id_filtextbox__port.text
                property alias username: id_filtextbox__username.text
                property alias password: id_filtextbox__password.text
                Item {
                    width: id_grid__agent.itemWidth
                    height: id_grid__agent.itemHeight
                    RowLayout {
                        anchors.fill: parent
                        spacing: 5
                        Item {
                            Layout.preferredWidth: id_grid__agent.itemTextWidth
                            Layout.preferredHeight: parent.height
                            Layout.alignment: Qt.AlignVCenter
                            FilText {
                                anchors.verticalCenter: parent.verticalCenter
                                text: qsTr("Server")
                            }
                        }
                        FilTextBox {
                            id: id_filtextbox__server
                            Layout.fillWidth: true
                            Layout.preferredHeight: parent.height
                            placeholderText: qsTr("Input the Address IP")
                        }
                    }
                }
                Item {
                    width: id_grid__agent.itemWidth
                    height: id_grid__agent.itemHeight
                    RowLayout {
                        anchors.fill: parent
                        Item {
                            Layout.preferredWidth: id_grid__agent.itemTextWidth
                            Layout.preferredHeight: parent.height
                            Layout.alignment: Qt.AlignVCenter
                            FilText {
                                anchors.verticalCenter: parent.verticalCenter
                                text: qsTr("Port")
                            }
                        }
                        FilTextBox {
                            id: id_filtextbox__port
                            Layout.fillWidth: true
                            Layout.preferredHeight: parent.height
                        }
                    }
                }
                Item {
                    width: id_grid__agent.itemWidth
                    height: id_grid__agent.itemHeight
                    RowLayout {
                        anchors.fill: parent
                        spacing: 5
                        Item {
                            Layout.preferredWidth: id_grid__agent.itemTextWidth
                            Layout.preferredHeight: parent.height
                            Layout.alignment: Qt.AlignVCenter
                            FilText {
                                anchors.verticalCenter: parent.verticalCenter
                                text: qsTr("UserName")
                            }
                        }
                        FilTextBox {
                            id: id_filtextbox__username
                            Layout.fillWidth: true
                            Layout.preferredHeight: parent.height
                        }
                    }
                }
                Item {
                    width: id_grid__agent.itemWidth
                    height: id_grid__agent.itemHeight
                    RowLayout {
                        anchors.fill: parent
                        Item {
                            Layout.preferredWidth: id_grid__agent.itemTextWidth
                            Layout.preferredHeight: parent.height
                            Layout.alignment: Qt.AlignVCenter
                            FilText {
                                anchors.verticalCenter: parent.verticalCenter
                                text: qsTr("Password")
                            }
                        }
                        FilTextBox {
                            id: id_filtextbox__password
                            Layout.fillWidth: true
                            Layout.preferredHeight: parent.height
                        }
                    }
                }
            }
        }
        NetworkCallable {
            id: id_networkcallable_test
            onStart: {
                id_filframe__agent.testing = true
            }
            onFinish: {
                id_filframe__agent.testing = false
            }
            onError: (status, errorString, result) => {
                showError("%1;%2;%3".arg(status).arg(errorString).arg(result))
                id_filframe__agent.lastTestResult = false
            }
            onSuccess: {
                showSuccess(qsTr("Connection Successful"))
                id_filframe__agent.lastTestResult = true
                id_filframe__agent.server = id_grid__agent.server
                id_filframe__agent.port = id_grid__agent.port
                id_filframe__agent.username = id_grid__agent.username
                id_filframe__agent.password = id_grid__agent.password
            }
        }
        FilContentDialog {
            id: id_filcontentdialog__restart
            title: qsTr("Friendly Reminder")
            message: qsTr("This action requires a restart of the program to take effect, is it restarted?")
            buttonFlags: FilContentDialogType.NegativeButton | FilContentDialogType.PositiveButton
            negativeText: qsTr("Cancel")
            positiveText: qsTr("OK")
            onPositiveClicked: {
                Qt.exit(931)
            }
        }
        function initAgentInfo() {
            var type = SettingsHelper.getAppAgentMode()
            switch (type) {
            case NetworkProxyType.HttpProxy: {
                id_filcombobox__agentMode.currentIndex = 1
                break
            }
            case NetworkProxyType.Socks5Proxy: {
                id_filcombobox__agentMode.currentIndex = 2
                break
            }
            case NetworkProxyType.NoProxy: {
                id_filcombobox__agentMode.currentIndex = 0
                break
            }
            default: {
                id_filcombobox__agentMode.currentIndex = 0
                break
            }
            }
            var server = SettingsHelper.getAppAgentServer()
            var port   = SettingsHelper.getAppAgentPort()
            var username = SettingsHelper.getAppAgentUsername()
            var password = SettingsHelper.getAppAgentPassword()
            id_grid__agent.server = server
            id_grid__agent.port   = port
            id_grid__agent.username = username
            id_grid__agent.password = password
            if (type !== NetworkProxyType.NoProxy) {
                Network.setApplicationProxy(type, server, Number(port), username, password)
            }
        }

        Component.onCompleted: {
            initAgentInfo()
        }
    }
}
